﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BookSourceVerification.utils;

public class JsonFileUtils : IDisposable
{
    private JsonTextWriter _jsonTextWriter;
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    public JsonFileUtils(TextWriter textWriter)
    {
        _jsonTextWriter = new JsonTextWriter(textWriter);
        _jsonTextWriter.WriteStartArray();
    }

    public async void AddNode(JObject node)
    {
        await _semaphore.WaitAsync();
        try
        {
            await node.WriteToAsync(_jsonTextWriter);
        }
        finally
        {
            _semaphore.Release();
        }
    }

    public async void Dispose()
    {
        await _jsonTextWriter.WriteEndArrayAsync();
        await _jsonTextWriter.FlushAsync();
        await _jsonTextWriter.CloseAsync();
    }

}